import { _decorator, Component, instantiate, Node, Prefab, Vec3 } from 'cc';
import Combat from './Combat';
import EventMgr from './event/EventMgr';
import { EventId } from './event/EventId';
import BattleUnit from './BattleUnit';
import { BattleUnitShow } from './show/BattleUnitShow';
import { I_ActionMsg } from './BattleConst';
import MathUtil from './util/MathUtil';
const { ccclass, property } = _decorator;

@ccclass('BattleManager')
/**战斗表现管理器，不参与计算，只做界面显示管理 */
export class BattleManager extends Component {
    @property(Node)
    roleBox: Node;
    @property(Prefab)
    rolePrefab: Prefab;

    private roleDic: Map<string, BattleUnitShow> = new Map();
    start() {
        //监听战斗发来的事件
        EventMgr.ins.on(EventId.ADD_ROLE, this.addRole, this)
        EventMgr.ins.on(EventId.DO_BATTLE, this.doBattle, this)

        new Combat().init();
    }

    private addRole(param: BattleUnit) {
        let uid = param.uid;
        let rolePrefab = instantiate(this.rolePrefab);
        let role = rolePrefab.addComponent(BattleUnitShow);
        this.roleDic.set(uid, role);
        this.roleBox.addChild(rolePrefab);
        role.init(param);
        rolePrefab.setPosition(new Vec3(param.pos.x, param.pos.y, 0));
    }

    private doBattle(param: I_ActionMsg): void {
        let castData = param.action;
        let targetData = param.targets[0];
        let action = param.subActions[0];
        let caster = this.roleDic.get(castData.uid);
        let target = this.roleDic.get(targetData.uid);
        let tPos = target.node.position;
        //两个距离比攻击距离大
        caster.moveTo(new Vec3(tPos.x + targetData.dic * action.attackDic, tPos.y, 1), () => {
            //走到位置攻击
            caster.doAtk(() => {
                //伤害帧触发
                console.log("触发攻击")
                //受击方受击
                target.beHurt(action.hurtNum);
                //飘字


            }, () => {
                //回原位
                caster.moveBack(() => {
                    //全部做完通知逻辑层
                    EventMgr.ins.event(EventId.DO_BATTLE_END)
                })
            })
        })

    }

    update(deltaTime: number) {

    }
}


